package com.chcit.mobile.mvp.receive.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.GravityEnum;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.loader.QuickLoader;
import com.xuexiang.xui.widget.spinner.editspinner.EditSpinner;
import com.chcit.custom.view.text.AutofitTextView;
import com.chcit.custom.view.text.one.SuperTextView;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.di.component.DaggerReceiveDetailComponent;
import com.chcit.mobile.di.module.ReceiveDetailModule;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.common.adapter.MonitorCodeAdapter;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.entity.Locator;
import com.chcit.mobile.mvp.entity.MonitorCode;
import com.chcit.mobile.mvp.entity.Reason;
import com.chcit.mobile.mvp.entity.ReceiveBean;
import com.chcit.mobile.mvp.receive.contract.ReceiveDetailContract;
import com.chcit.mobile.mvp.receive.presenter.ReceiveDetailPresenter;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 入库详情页面(非标准版）
 */
public class ReceiveOldDetailFragment extends ScanFragment<ReceiveDetailPresenter> implements ReceiveDetailContract.View {

    @BindView(R.id.tv_purchase_detail_index)
    TextView tvIndex;
    /*  @BindView(R.id.tv_purchase_detail_productName)
      TextView tvProduct;*/
    @BindView(R.id.tv_purchase_detail_productSpec)
    TextView tvProductSpec;
    @BindView(R.id.tv_purchase_detail_manufacturer)
    TextView tvManufacturer;
    @BindView(R.id.tv_purchase_detail_productCode)
    TextView tvProductCode;
    @BindView(R.id.tv_purchase_detail_uom)
    TextView tvUom;
    @BindView(R.id.tv_purchase_detail_lot)
    TextView tvLot;
    @BindView(R.id.tv_purchase_detail_guaranteeDate)
    TextView tvGuaranteeDate;
    @BindView(R.id.tv_purchase_detail_pricePO)
    SuperTextView tvPricePO;
    @BindView(R.id.tv_purchase_detail_productName)
    AutofitTextView tvProductName;
    @BindView(R.id.tv_purchase_detail_priceOrder)
    SuperTextView tvPriceOrder;
    @BindView(R.id.tv_purchase_detail_vendor)
    TextView tvVendor;
    @BindView(R.id.tv_purchase_detail_qtyArrived)
    TextView tvQtyArrived;
    @BindView(R.id.tv_purchase_detail_inventory)
    TextView tvPackageQty;//大包装数
    @BindView(R.id.tv_purchase_detail_taxInvoiceNo)
    TextView tvTaxInvoiceNo;//发票号
    @BindView(R.id.ll_purchase_detail_taxInvoiceNo)
    LinearLayout llTaxInvoiceNo;//
    @BindView(R.id.tv_purchase_detail_qtyConfirmed)
    AppCompatEditText etQtyConfirmed;
    @BindView(R.id.et_purchase_detail_qtyRejected)
    AppCompatEditText etQtyRejected;
    @BindView(R.id.spinner_purchase_detail_rejectReason)
    MaterialSpinner spinnerRejectReason;
    @BindView(R.id.spinner_purchase_detail_locator)
    EditSpinner spinnerLocator;
    @BindView(R.id.et_purchase_detail_invoiceNo)
    EditText etInvoiceNo;
    @BindView(R.id.bt_purchase_detail_cancel)
    Button btCancel;
    @BindView(R.id.bt_purchase_detail_ok)
    Button btOk;
    @BindView(R.id.ll_receive_seventh)
    LinearLayout llOddUnit;
    @BindView(R.id.tv_purchase_detail_unit)
    TextView tvUnit;
    @BindView(R.id.tv_purchase_detail_odd)
    TextView tvOdd;
    @Inject
    List<Reason> reasons;
    @Inject
    List<Locator> locators;
    @BindView(R.id.include_receive)
    LinearLayout includeReceive;
    @BindView(R.id.tv_reject_detail_receving)
    TextView tvRejectReceving;//拒收仓库

    @BindView(R.id.tv_reject_detail_reason)
    AppCompatTextView tvRejectReason;
    @BindView(R.id.tv_reject_detail_qtyLeft)
    TextView tvRejectQtyLeft;
    @BindView(R.id.et_reject_detail_qtyConfirmed)
    AppCompatEditText etRejectQtyConfirmed;
    @BindView(R.id.include_reject_receive)
    LinearLayout includeRejectReceive;
    private ReceiveBean receiveBean;
    private MenuTypeEnum type;
    private Locator locator;//设置的货位

    public static ReceiveOldDetailFragment newInstance(ReceiveBean receiveBean, MenuTypeEnum type) {
        ReceiveOldDetailFragment fragment = new ReceiveOldDetailFragment();
        fragment.receiveBean = receiveBean;
        fragment.type = type;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerReceiveDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .receiveDetailModule(new ReceiveDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_receive_detail, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        setData();
        initSpinner();

    }

    private void initSpinner() {

        locators = new ArrayList<>();//Arrays.asList("默认货位","理货货位","中药货位");
        JSONObject data = new JSONObject();
        data.put("productId", receiveBean.getProductId());
        data.put("showStorageLoc", "");//默认货位
        assert mPresenter != null;
        mPresenter.getLocators(data, status -> {
            locators.addAll(status);
            spinnerLocator.setItemData(locators);
            locator = status.get(0);
//            if(ObjectUtils.anyNotNull(locator)){
//                spinnerLocator.setText(locator.getName());
//            }
            spinnerLocator.setImageOnClickListener(new View.OnClickListener() {
                int i = 0;
                @Override
                public void onClick(View v) {
                    if (i == 0) {
                        i++;
                        JSONObject data = new JSONObject();
                        data.put("productId", receiveBean.getProductId());
                        data.put("showStorageLoc", "Y");//在库货位
                        assert mPresenter != null;
                        mPresenter.getLocators(data, list -> {
                            if (list.contains(locator)) {
                                locators = list;
                            } else {
                                locators.addAll(list);
                            }
                            locator = locators.get(0);
                            spinnerLocator.setItemData(locators);
                            spinnerLocator.getBaseAdapter().notifyDataSetChanged();

                        });
                    }
                }
            });
            spinnerLocator.setOnItemClickListener((parent, view, position, id) -> {
                if (position >= 0) {
                    locator = spinnerLocator.getSelectItem();
                }
            });
        });
    }

    @SuppressLint("SetTextI18n")
    private void setData() {
        mCommonToolbar.setTitleText(type.getDesc());
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            assert mPresenter != null;
            if (mPresenter.isError) {
                setFragmentResult(RESULT_OK, new Bundle());
            }
            pop();
        });
        switch (type) {
            case PURCHASE_CHECK:

                includeReceive.setVisibility(View.VISIBLE);
                includeRejectReceive.setVisibility(View.GONE);
                tvUnit.setText((receiveBean.getUnitPackageCount() + "包/" + receiveBean.getUnitQty() + receiveBean.getUomName()));
                tvOdd.setText((receiveBean.getOddQty() + receiveBean.getUomName()));
                assert mPresenter != null;
                mPresenter.getReasons(spinnerRejectReason);
                break;
            case PURCHASE_RECEIVE:

                includeReceive.setVisibility(View.VISIBLE);
                includeRejectReceive.setVisibility(View.GONE);
                tvUnit.setText((receiveBean.getUnitPackageCount() + "包/" + receiveBean.getUnitQty() + receiveBean.getUomName()));
                tvOdd.setText(( receiveBean.getOddQty() + receiveBean.getUomName()));
                assert mPresenter != null;
                mPresenter.getReasons(spinnerRejectReason);
                break;
            case YN_CHECK:
                includeReceive.setVisibility(View.VISIBLE);
                includeRejectReceive.setVisibility(View.GONE);
                llOddUnit.setVisibility(View.GONE);
                mCommonToolbar.setTitleText(receiveBean.getASNTypeName() + "验收");
                assert mPresenter != null;
                mPresenter.getReasons(spinnerRejectReason);
                break;
            case YN_RECEIVE:
                includeReceive.setVisibility(View.VISIBLE);
                includeRejectReceive.setVisibility(View.GONE);
                llOddUnit.setVisibility(View.GONE);
                mCommonToolbar.setTitleText(receiveBean.getASNTypeName() + "入库");
                assert mPresenter != null;
                mPresenter.getReasons(spinnerRejectReason);
                break;
            case REJECT:
                includeReceive.setVisibility(View.GONE);
                includeRejectReceive.setVisibility(View.VISIBLE);
                mCommonToolbar.setTitleText("拒收入库");
                spinnerLocator.getEditText().setEnabled(false);
                tvRejectReceving.setText(receiveBean.getWarehouseName());
                tvRejectQtyLeft.setText(receiveBean.getQtyLeft().toString());
                tvRejectReason.setText(receiveBean.getRejectReasonName());
                etRejectQtyConfirmed.setText(receiveBean.getQtyLeft().toString());
                etRejectQtyConfirmed.setEnabled(false);
                initRejectEvent();
                break;
        }
        TextView rithtTextview = mCommonToolbar.getRightMenuView(0);
        rithtTextview.setText("下一个");
        rithtTextview.setOnClickListener(l -> {
            setFragmentResult(-2, null);
            pop();
        });
        if (receiveBean.getPriceActual().compareTo(receiveBean.getPriceActual()) != 0) {
            tvPricePO.setCenterTextColor(getResources().getColor(R.color.Red));
            tvPriceOrder.setCenterTextColor(getResources().getColor(R.color.Red));
        }
        tvIndex.setText(receiveBean.getAsnNo());
        tvProductName.setText(receiveBean.getProductName());
        tvProductSpec.setText(receiveBean.getProductSpec());
        tvManufacturer.setText(receiveBean.getManufacturer());
        tvProductCode.setText(receiveBean.getProductCode());//不清楚 ？
        tvUom.setText(receiveBean.getUomName());
        tvLot.setText(receiveBean.getLot());
        tvGuaranteeDate.setText(receiveBean.getGuaranteeDate());
        tvPackageQty.setText(String.valueOf(receiveBean.getLPackageQty()));
        tvPricePO.setCenterString((receiveBean.getPriceActual() + "元"));//?
        tvPriceOrder.setCenterString((receiveBean.getPriceActual() + "元"));
        tvVendor.setText(receiveBean.getBpartnerName());
        tvQtyArrived.setText((receiveBean.getQtyArrived().intValue() + ""));
        etQtyConfirmed.setText((receiveBean.getQtyArrived().intValue() + ""));
        if(StringUtils.isNotEmpty(receiveBean.getTaxInvoiceNo())){
            llTaxInvoiceNo.setVisibility(View.VISIBLE);
            tvTaxInvoiceNo.setText(receiveBean.getTaxInvoiceNo());
        }
        etQtyRejected.setText("0");
        // spinnerQtyRejected.setText(receiveBean.getUomName());
        // etLocator.setText(receiveBean.g);
        //etInvoiceNo.setText(receiveBean.getTaxInvoiceNo());
        etQtyConfirmed.addTextChangedListener(new TextWatcher() {
            String beforeText;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                doAfterTextChanged(s, beforeText, etQtyConfirmed, etQtyRejected);
            }
        });

        etQtyRejected.addTextChangedListener(new TextWatcher() {
            String beforeText;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                doAfterTextChanged(s, beforeText, etQtyRejected, etQtyConfirmed);
            }
        });
    }

    private void initRejectEvent() {

        etRejectQtyConfirmed.setOnClickListener(l -> {
            etRejectQtyConfirmed.setText(Objects.requireNonNull(etRejectQtyConfirmed.getText()).toString());//添加这句后实现效果
            Spannable content = etRejectQtyConfirmed.getText();
            Selection.selectAll(content);
        });

        etRejectQtyConfirmed.addTextChangedListener(new TextWatcher() {
            String beforeText;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                beforeText = s.toString();
            }


            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etRejectQtyConfirmed.hasFocus()) {
                    String data = s.toString();
                    try {
                        BigDecimal number = new BigDecimal(0);
                        if (!data.isEmpty()) {
                            number = new BigDecimal(data);
                        }
                        if (number.compareTo(receiveBean.getQtyLeft()) > 0) {
                            DialogUtil.showErrorDialog(mContext, "退回数量必须小于等于拒收数量！");
                            etRejectQtyConfirmed.setText(beforeText);
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

    }

    private void doAfterTextChanged(Editable s, String beforeText, EditText nowEdit, EditText newText) {
        String data = s.toString();
        if (nowEdit.hasFocus() && !data.equals(beforeText)) {

            try {
                BigDecimal received = new BigDecimal(0);
                if (!data.isEmpty()) {
                    received = new BigDecimal(data);
                }
                BigDecimal number = receiveBean.getQtyArrived().subtract(received);
                if (number.intValue() < 0) {
                    DialogUtil.showErrorDialog(getContext(), "实收数量必须小于等于到货数量！");
                    nowEdit.setText(beforeText);
                    return;
                }
                newText.setText((number + ""));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        int position = locators.indexOf(new Locator(barcodeData));
        if (position != -1) {
            spinnerLocator.setText(barcodeData);
            locator = locators.get(position);

        } else {

            assert mPresenter != null;
            JSONObject params = new JSONObject();
            params.put("value", barcodeData);
            mPresenter.getLocators(params, list -> {
                locator = list.get(0);
                locators.addAll(list);
                spinnerLocator.setText(barcodeData);
            });
        }
    }

    @OnClick({R.id.bt_purchase_detail_cancel, R.id.bt_purchase_detail_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_purchase_detail_cancel:
                isScanSupervision = true;
           /*     if(shipmentBean.getSupervisionCodes()!=null){
                    monitorCodeAdapter.getData().addAll(monitorCodes);
                }*/
                assert mPresenter != null;
                mPresenter.getMonitorCodes(receiveBean.getAsnLineId(), list -> {
                    monitorCodes.clear();
                    monitorCodes.addAll(list);
                    monitorCodeAdapter.notifyDataSetChanged();
                });
                buder.show();
                break;
            case R.id.bt_purchase_detail_ok:
                //  DialogUtil.showMsgDialog(getContext(),"",receiveBean.toString());
                if (spinnerLocator.getText().isEmpty()) {
                    DialogUtil.showErrorDialog(getContext(), "请输入货位！");
                    return;
                }
                if("Y".equals(receiveBean.getIsNeerGuarantee())){
                    new MaterialDialog.Builder(mContext)
                            .title("提示")
                            .content(receiveBean.getError()+",是否继续")
                            .positiveText("是")
                            .negativeText("否")
                            .onPositive((dialog, which) -> {
                                if (type.equals(MenuTypeEnum.REJECT)) {
                                    doRejectConfirm();
                                } else {
                                    doConfirm(locator.getLocatorId());
                                }
                            }).show();

                }else{
                    if (type.equals(MenuTypeEnum.REJECT)) {
                        doRejectConfirm();
                    } else {
                        doConfirm(locator.getLocatorId());
                    }
                }



        }
    }

    private void doRejectConfirm() {
        JSONObject data = new JSONObject();
        JSONArray asnLineIds = new JSONArray();
        asnLineIds.add(receiveBean.getAsnLineId());
        data.put("asnLineId", asnLineIds);

        /*if ("Y".equals(receiveBean.getIsControlledProduct())) {
            OldReceiveFragment receiveFragment = findFragment(OldReceiveFragment.class);
            if (receiveFragment != null && receiveFragment.getUser() == null) {
                HttpClientHelper.showSelectSecondChangeDialog(getActivity(), (dialog, user) -> {
                    receiveFragment.setUser(user);
                    data.put("workerId2", receiveFragment.getUser().getId());
                    submit(data, HttpMethodContains.REJECT_OK);
                });
                return;
            }

            data.put("workerId2", receiveFragment.getUser().getId());

        }*/
        submit(data, HttpMethodContains.REJECT_OK);
    }

    private void doConfirm(int locatorId) {
        int asnId = receiveBean.getAsnId();
        int asnLineId = receiveBean.getAsnLineId();
        String qtyReceived = Objects.requireNonNull(etQtyConfirmed.getText()).toString();
        String rejectSty = Objects.requireNonNull(etQtyRejected.getText()).toString();
        int rejectQty = 0;
        if (!rejectSty.isEmpty()) {
            rejectQty = Integer.parseInt(rejectSty);
        }
        String rejectReason = reasons.get(spinnerRejectReason.getSelectedIndex()).getValue();
        if (rejectQty > 0 && rejectReason == null) {
            DialogUtil.showErrorDialog(getContext(), "请选择拒收原因");
            return;
        }
        JSONObject data = new JSONObject();
        data.put("asnId", asnId);//
        data.put("asnLineId", asnLineId);
        data.put("rejectQty", rejectQty);
        data.put("locatorId", locatorId);
        data.put("qtyReceived", qtyReceived);
        data.put("rejectReason", rejectReason);
//        data.put("asnLineID", asnLineId);
//        data.put("rejectqty", rejectQty);
//        data.put("locatorID", locatorId);
//        data.put("storageStatus",receiveBean.getStorageStatus());
//        data.put("qty", qtyReceived);
//        data.put("rejectReason", rejectReason);
        if ("Y".equals(receiveBean.getIsControlledProduct())) {
            OldReceiveFragment oldReceiveFragment = (OldReceiveFragment) getPreFragment();
            if (oldReceiveFragment != null && oldReceiveFragment.getUser() == null) {
                HttpClientHelper.showSelectSecondChangeDialog(getActivity(), (dialog, user) -> {
                    oldReceiveFragment.setUser(user);
                    data.put("workerId2", oldReceiveFragment.getUser().getId());
                    submit(data, HttpMethodContains.CHECK_RECEIVE_OK);
                });
                return;
            }

            data.put("workerId2", oldReceiveFragment.getUser().getId());

        }
        submit(data, HttpMethodContains.CHECK_RECEIVE_OK);

    }

    private void submit(JSONObject data, String checkReceiveOk) {
        assert mPresenter != null;
        mPresenter.doConfirm(checkReceiveOk, data, () -> {
            setFragmentResult(RESULT_OK, null);
            pop();
        });
    }

    private void submit(JSONObject data) {
        assert mPresenter != null;
        //验收确认
        mPresenter.preCheckRecieve(data, () -> {
            showMessage("处理成功");
            setFragmentResult(RESULT_OK, new Bundle());
            pop();
        });
    }

    @Override
    public void onDestroy() {
        spinnerLocator = null;
        super.onDestroy();


    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        if ("SR".equals(receiveBean.getASNType())) {
            initScanDialog();
        } else {
            btCancel.setEnabled(false);
        }
    }

    private MaterialDialog buder;
    private SuperInputEditText etSupervision;
    private MonitorCodeAdapter monitorCodeAdapter;
    private List<MonitorCode> monitorCodes = new ArrayList<>();
    boolean isScanSupervision = false;//是否是扫描监管码

    void initScanDialog() {

        monitorCodeAdapter = new MonitorCodeAdapter(monitorCodes);
        buder = new MaterialDialog.Builder(mContext)
                .title("监管码绑定")
                .titleGravity(GravityEnum.CENTER)
                .customView(R.layout.dialog_scan_ok, true)
                .positiveText("确认")
                //.negativeText("取消")
                .autoDismiss(false)
                .onAny((dialog, which) -> {
                    isScanSupervision = false;
                    if (which == DialogAction.POSITIVE) {
                        //pickListMaId:1212,monitoringCode:['1111','1234','4444']
                        JSONArray monitoringCode = new JSONArray();
                        for (MonitorCode m : monitorCodes) {
                            if (m.getId() > 0) {
                                monitoringCode.add(m.getCode());
                            }

                        }
                        if (monitoringCode.size() > 0) {
                            JSONObject data = new JSONObject();
                            data.put("asnLineId", receiveBean.getAsnLineId());
                            data.put("monitoringCode", monitoringCode);
                            assert mPresenter != null;
                            mPresenter.doConfirm(HttpMethodContains.RECEIVE_CODE_CREATE, data, dialog::dismiss);
                        }

                    } else if (which == DialogAction.NEGATIVE) {
                        // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                        monitorCodeAdapter.getData().clear();
                        monitorCodeAdapter.notifyDataSetChanged();
                    }
                    //dialog.dismiss();
                })
                .build();


        //初始化Adapter
        assert buder.getCustomView() != null;
        RecyclerView recyclerView = buder.getCustomView().findViewById(R.id.rv_purchase_scan_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));

        ItemDragAndSwipeCallback mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(monitorCodeAdapter);
        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(recyclerView);
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                //                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                //                holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
            private int position = -1;

            @Override
            public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
                position = pos;
            }

            @Override
            public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            //删除item
            @Override
            public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
                //{pickListMaId:1212,monitoringCode:1111}
                if (pos != -1) {
                    position = pos;
                }
                MonitorCode m = monitorCodes.get(position);
                if (m.getId() == 0) {
                    JSONObject data = new JSONObject();
                    data.put("asnLineId", receiveBean.getAsnLineId());
                    data.put("monitoringCode", m.getCode());
                    assert mPresenter != null;
                    mPresenter.doConfirm(HttpMethodContains.RECEIVE_CODE_DELETE, data, () -> {

                    });
                }
                //{pickListMaId:1212,monitoringCode:1111}

            }

            @Override
            public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
                canvas.drawColor(ContextCompat.getColor(mContext, R.color.green));

            }
        };

        //mItemDragAndSwipeCallback.setDragMoveFlags(ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN);
        mItemDragAndSwipeCallback.setSwipeMoveFlags(ItemTouchHelper.START | ItemTouchHelper.END);
        // 开启滑动删除
        monitorCodeAdapter.enableSwipeItem();
        monitorCodeAdapter.setOnItemSwipeListener(onItemSwipeListener);
        // 开启拖拽
        monitorCodeAdapter.enableDragItem(mItemTouchHelper);
        monitorCodeAdapter.setOnItemDragListener(listener);
        recyclerView.setAdapter(monitorCodeAdapter);
        Button button = buder.getCustomView().findViewById(R.id.button_scan_clear);
        button.setOnClickListener(l -> {
            monitorCodeAdapter.getData().clear();
            monitorCodeAdapter.notifyDataSetChanged();
        });
        etSupervision = buder.getCustomView().findViewById(R.id.et_receiveScanCode_list_SerNo);
        etSupervision.setOnKeyListener((v, keyCode, event) -> {

            if (keyCode == KeyEvent.KEYCODE_ENTER && !Objects.requireNonNull(etSupervision.getText()).toString().isEmpty()) {

                addBindData();
                return true;
            } else {
                return false;
            }

        });

    }

    private void addBindData() {
        String barcodeData = Objects.requireNonNull(etSupervision.getText()).toString();
        MonitorCode supervisionCode = new MonitorCode(receiveBean.getAsnLineId(), barcodeData);

        if (monitorCodeAdapter.getData().contains(supervisionCode)) {
            Toast.makeText(mContext, "绑定的数据重复！", Toast.LENGTH_LONG).show();
            return;
        }
        monitorCodeAdapter.addData(supervisionCode);

    }


}
